<template>
  <div style="border: 1px solid #ccc; width: 100%">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
    <!-- @onChange="onChange" -->
    <Editor
      style="height: 500px; overflow-y: hidden"
      :model-value="props.modelValue"
      :defaultConfig="editorConfig"
      mode="default"
      @onChange="onChange"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script setup lang="ts">
import { CODE_SUCCESS } from "@/utils/service"
import { onBeforeUnmount, shallowRef } from "vue"
import { ElMessage } from "element-plus"
import { getImgApi } from "@/api/common"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import { IDomEditor } from "@wangeditor/editor"

// 富文本
// 编辑器实例，必须用 shallowRef
const props = defineProps({
  modelValue: String
})
const emit = defineEmits(["update:modelValue"])
const onChange = (editor: IDomEditor) => {
  emit("update:modelValue", editor.getHtml())
}
const editorRef = shallowRef()
const toolbarConfig = {
  excludeKeys: ["group-video"]
}
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "/api/uploadImg",
      fieldName: "file",
      async customInsert(res: ApiResponseData<any>, insertFn: Function) {
        if (res.code === CODE_SUCCESS) {
          const { data: url } = await getImgApi({ path: res.data })
          if (url) {
            insertFn(url, null, url)
          } else {
            ElMessage.error("插入图片失败！")
          }
        }
      }
    },
    uploadVideo: {
      server: "/api/uploadImg",
      fieldName: "file",
      async customInsert(res: ApiResponseData<any>, insertFn: Function) {
        if (res.code === CODE_SUCCESS) {
          const { data: url } = await getImgApi({ path: res.data })
          if (url) {
            insertFn(url, null, url)
          } else {
            ElMessage.error("插入图片失败！")
          }
        }
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
